<template>
    <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120"
            class="m-t20"
    >
        <el-form-item label="项目类型" prop="projectTypeId">
            <el-select v-model="form.projectTypeId" clearable class="input-width">
                <el-option v-for="(item,index) in data.projectType" :key="index" :label="item.enumName" :value="item.enumId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="项目集" prop="projectSetId">
            <el-select v-model="form.projectSetId" clearable class="input-width">
                <el-option v-for="(item,index) in data.projectSetList" :key="index" :label="item.projectSetName" :value="item.projectSetId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="责任部门" prop="responsibleDepartmentId">
            <el-select
                    clearable class="input-width"
                    v-model="form.responsibleDepartmentId"
                    @change="departmentChange"
            >
                <el-option v-for="(item,index) in data.allDepartmentList" :key="index" :label="item.departmentName" :value="item.departmentId"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="发起人" prop="responsibleUserId">
            <el-select
                    clearable class="input-width"
                    v-model="form.responsibleUserId"
            >
                <el-option v-for="(item,index) in state.departmentPersonList" :key="index" :label="item.userName" :value="item.userId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
            <el-input v-model.trim="form.projectName" clearable class="input-width" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="行业类型" prop="industryTypeId">
            <el-select v-model="form.industryTypeId" class="input-width" clearable>
                <el-option v-for="(item,index) in data.industryList" :key="index" :label="item.enumName" :value="item.enumId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="投资类型" prop="investmentType">
            <el-select v-model="form.investmentType" class="input-width" clearable>
                <el-option label="全资" :value="1"></el-option>
                <el-option label="控股" :value="2"></el-option>
                <el-option label="参股" :value="3"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="合作方" prop="partnerId">
            <el-select v-model="form.partnerId" class="input-width" clearable>
                <el-option v-for="(item,index) in data.partnerList" :key="index" :label="item.partnerName" :value="item.partnerId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="预计总投" prop="projectAmount">
            <el-input v-model="form.projectAmount" clearable class="input-width" placeholder="请输入预计总投"></el-input>
        </el-form-item>
        <el-form-item label="实施主体" prop="companyId">
            <el-select v-model="form.companyId" class="input-width" clearable>
                <el-option v-for="(item,index) in data.companyList" :key="index" :label="item.companyName" :value="item.companyId"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="计划情况" prop="planStatus">
            <el-select v-model="form.planStatus" class="input-width" clearable>
                <el-option label="计划外" :value="-1"></el-option>
                <el-option label="计划内" :value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="可研报告" prop="urlKey">
            <el-upload
                    ref="uploadRef"
                    action="#"
                    :http-request="uploadFile"
                    :on-remove="onRemove"
            >
                <el-button style="background-color: #fff8f6;border-color: #FC7018;color: #FC7018;">
                    <svg-icon icon-class="project-detail-icon-l-shangchuan" class="upload-icon m-r5"></svg-icon>
                    点击上传
                </el-button>
            </el-upload>
        </el-form-item>
    </el-form>
    <div class="buttons-wrap d-flex j-center m-t20">
        <el-button
            color="#FC7018"
            style="color: #FFFFFF"
            @click="nextStep"
        >下一步</el-button>
    </div>
</template>

<script setup>
import {ElForm, ElFormItem, ElLoading, ElMessage, ElOption, ElSelect, ElUpload} from "element-plus";
import {inject, reactive, ref, watch} from "vue";
import {department} from "@/api/project";
import {reserveInvestmentProjectLibraryApi} from "@/api/investment";

const data = inject('state');

const form = reactive({
    projectTypeId:'',
    projectName:'',
    industryTypeId:'',
    investmentType:'',
    partnerId:'',
    projectAmount:'',
    companyId:'',
    planStatus:'',
    urlKey:'',
    responsibleDepartmentId:'',
    responsibleUserId:'',
    projectId:'',
    projectSetId:''
});

const rules = reactive({
    projectTypeId: [
        { required: true, message: '项目类型不能为空!', trigger: 'change' },
    ],
    projectName: [
        { required: true, message: '项目名称不能为空!', trigger: 'blur' },
    ],
    industryTypeId: [
        { required: true, message: '行业类型不能为空!', trigger: 'change' },
    ],
    investmentType: [
        { required: true, message: '投资类型不能为空!', trigger: 'change' },
    ],
    partnerId: [
        { required: true, message: '合作方不能为空!', trigger: 'change' },
    ],
    projectAmount: [
        { required: true, message: '预计总投不能为空!', trigger: 'blur' },
    ],
    companyId: [
        { required: true, message: '实施主体不能为空!', trigger: 'change' },
    ],
    planStatus: [
        { required: true, message: '计划情况不能为空!', trigger: 'change' },
    ],
    responsibleDepartmentId: [
        { required: true, message: '责任部门不能为空!', trigger: 'change' },
    ],
    responsibleUserId: [
        { required: true, message: '发起人不能为空!', trigger: 'change' },
    ],
    projectSetId: [
        { required: true, message: '项目集不能为空!', trigger: 'change' },
    ],
    urlKey: [
        { required: true, message: '可研报告不能为空!', trigger: 'change' },
    ],
});

const state = reactive({
    projectId:'',
    programmeInfo:null,
    departmentPersonList:[],
    form:{}
});


/**
 * 根据部门id查负责人
 * @param responsibleDepartmentId
 */
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
    department.getLeaderByDepartmentId(responsibleDepartmentId).then((res) => {
        const { code, msg } = res;
        if (code == 200) {
            state.departmentPersonList = res.data;
        }
    });
};

/**
 * 部门被选择
 */
const departmentChange = (e) => {
    if(e){
        getLeaderByDepartmentId(e);
    }
}

/**
 * el-upload 选择文件后的事件
 * @param file
 */
const uploadFile = (file) => {
    const loading = ElLoading.service({
        lock: true,
        text: '文件上传中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    let uploadFile = new FormData();
    uploadFile.append("file",file.file);
    reserveInvestmentProjectLibraryApi.upload(uploadFile).then(res=>{
        const { code,data } = res;
        if(code == 200){
            loading.close();
            ElMessage.success('上传成功!');
            form.urlKey = data;
            formRef.value.clearValidate('urlKey');
        }
    });
}

/**
 * el-upload 移除
 */
const onRemove = () => {
    form.urlKey = '';
    formRef.value.validateField('urlKey');
};

/**
 * 查询项目详情
 * @param projectId
 */
const getProjectInfo = (projectId) => {
    reserveInvestmentProjectLibraryApi.getProjectInfo({projectId:projectId})
        .then(res=>{
            const {code,data} = res;
            if(code == 200){
                state.form = data;
                if(data.responsibleDepartmentId!==''){
                    getLeaderByDepartmentId(data.responsibleDepartmentId);
                }
                for(let k1 in data){
                    for (let k2 in form){
                        if(k1 === k2){
                            form[k2] = data[k1];
                        }
                    }
                }
            }
        });
}

/**
 * 添加项目信息
 */
const addOne = (params,callback) => {
    reserveInvestmentProjectLibraryApi.addOne(params).then(res=>{
        const {code,data} = res;
        if(code == 200){
            if(callback)callback(data);
        }
    });
}

/**
 * 提交
 */
const formRef = ref(null);
const submit = (callback) => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            let newForm = JSON.parse(JSON.stringify(form));
            if(state.form.urlKey!==undefined && state.form.urlKey!==''){
                newForm.urlKey = '';
            }
            addOne(newForm,(data)=>{
                if(callback)callback(data);
            });
        } else {
            console.log('error submit!', fields)
        }
    })
}

/**
 * 下一步
 */
const emits = defineEmits(['nextStep']);
const nextStep = () => {
    submit((data)=>{
        emits('nextStep','goProjectStageTree',{projectId:data,projectTypeId:form.projectTypeId});
    });
}

watch(()=> [data.title,data.row],(value)=>{
    if(value[0]==='编辑' && value[1]!==null){
        getProjectInfo(value[1].projectId);
    }
},{deep: true,immediate:true})

/**
 * 重置表单
 */
const resetFields = () => {
  formRef.value.resetFields();
}

defineExpose({ resetFields });
</script>

<style lang="scss" scoped>
.input-width{
    width: 500px !important;
}
.upload-icon{
    width: 18px;
    height: 18px;
}
</style>